<template>
    <el-form label-width="100px">
        <el-form-item label="SPU名称">
            <el-input placeholder="请输入SPU名称" v-model="SpuParams.spuName"></el-input>
        </el-form-item>
        <el-form-item label="SPU品牌">
            <el-select style="width: 240px" v-model="SpuParams.tmId">
                <el-option v-for="(item,index) in AllTradeMarkList" :key="item.id" :label="item.tmName" :value="item.id"></el-option>
            </el-select>
        </el-form-item>
        <el-form-item label="SPU描述">
            <el-input type="textarea" placeholder="请输SPU描述" v-model="SpuParams.description"></el-input>
        </el-form-item>
        <el-form-item label="SPU图片">
            <!-- v-model:file-list展示默认图片 -->
            <el-upload
                v-model:file-list="imgList as UploadUserFile[]"
                action="/api/admin/product/fileUpload"
                list-type="picture-card"
                :on-preview="handlePictureCardPreview"
                :on-remove="handleRemove"
                :before-upload="handlerUpload"
            >
                <el-icon><Plus /></el-icon>
            </el-upload>

            <el-dialog v-model="dialogVisible">
                <img w-full :src="dialogImageUrl" alt="Preview Image" style="width: 100%; height: 100%;"/>
            </el-dialog>
        </el-form-item>
        <el-form-item label="SPU的销售属性">
            <!-- 展示销售属性的下拉菜单 -->
            <el-select v-model="saleAttrIdAndValueName" style="width: 240px" :placeholder="unSelectSaleAttr.length?`还未选择${unSelectSaleAttr.length}个`:'无'">
                <el-option :value="`${item.id}:${item.name}`" v-for="(item,index) in unSelectSaleAttr" :key="item.id" :label="item.name"></el-option>
            </el-select>
            <el-button @click="addSaleAttr" :disabled="saleAttrIdAndValueName?false:true"type="primary" icon="Plus" style="margin-left: 10px;">添加属性</el-button>
            <!-- 展示销售属性与属性值的地方 -->
            <el-table border style="margin: 10px 0;" :data="saleAttr">
                <el-table-column label="序号" type="index" align="center" width="80px"></el-table-column>
                <el-table-column label="销售属性名字" width="120px" prop="saleAttrName"></el-table-column>
                <el-table-column label="销售属性值">
                    <template #="{row,$index}">
                        <el-tag @close="row.spuSaleAttrValueList.splice($index,1)" style="margin: 0px 5px;" v-for="(item,index) in row.spuSaleAttrValueList" :key="item.id" closable>
                            {{ item.saleAttrValueName }}
                        </el-tag>
                        <el-input @blur="toLook(row)" v-model="row.saleAttrValue" v-if="row.flag==true" placeholder="请输入属性值" size="small" style="width: 100px;"></el-input>
                        <el-button @click="toEdit(row)" v-else type="primary" size="small" icon="Plus"></el-button>
                    </template>
                </el-table-column>
                <el-table-column label="操作" width="120px">
                    <template #="{row,$index}">
                        <el-button type="primary" size="small" icon="Delete" @click="saleAttr.splice($index,1)"></el-button>
                    </template>
                </el-table-column>
            </el-table>
        </el-form-item>
        <el-form-item>
            <el-button :disabled="saleAttr.length>0?false:true" type="primary" @click="save">保存</el-button>
            <el-button type="primary" @click="cancel">取消</el-button>
        </el-form-item>
    </el-form>
</template>
<script setup lang="ts">
import { HasSaleAttr, SaleAttr, SpuData, SpuImg } from '@/api/product/spu/type';
import { ref ,computed} from 'vue';
import { reqAllTradeMark,reqSpuHasSaleAttr,reqSpuImageList,reqAllSaleAttr,reqAddOrUpdateSpu } from '@/api/product/spu';
import { Trademark,AllTradeMark,SpuHasImg,SaleAttrResponseData ,HasSaleAttrResponseDate,SaleAttrValue} from '@/api/product/spu/type';
import { ElMessage, type UploadProps, type UploadUserFile } from 'element-plus'
let $emit=defineEmits(['changeScene']);
//子组件点击取消按钮，通知父组件切换场景
const cancel=()=>{
    $emit('changeScene',{flag: 0,params: 'update'});
}

//存储已有的SPU这些数据
let AllTradeMarkList=ref<Trademark[]>([])
//商品图片
let imgList=ref<SpuImg[]>([])
//已有的SPU销售属性
let saleAttr=ref<SaleAttr[]>([])
//全部的销售属性
let allSaleAttr=ref<HasSaleAttr[]>([])

//控制对话框的显示与隐藏效果
let dialogVisible=ref<boolean>(false);
//存储预览图片的地址
let dialogImageUrl=ref<string>("");


//存储已有的SPU对象
let SpuParams=ref<SpuData>({
    category3Id: '',
    spuName: '',
    description: '',
    tmId: '',
    spuImageList: [],
    spuSaleAttrList: [],
});
//将来收集还未选择的销售属性的ID与属性的名字
let saleAttrIdAndValueName=ref<string>('');















const initHasSpuData=async (spu:SpuData)=>{
    //存储已有的spu对象，将来展示
    SpuParams.value=spu
    //spu:父组件传过来的不完整的spu对象
    //获取全部的品牌的数据
    let result:AllTradeMark= await reqAllTradeMark();
    console.log("全部品牌数据");
    console.log(result);
    //获取某一个品牌旗下全部售卖商品的图片
    let result1:SpuHasImg=await reqSpuImageList(spu.id as number);
    console.log("商品图片");
    console.log(result1);
    //获取已有的spu销售属性数据
    let result2:SaleAttrResponseData=await reqSpuHasSaleAttr(spu.id as number);
    console.log("spu属性");
    console.log(result2);
    //获取整个项目全部SPU的销售属性
    let result3:HasSaleAttrResponseDate=await reqAllSaleAttr();
    console.log("全部销售属性")
    console.log(result3);

    //存储全部品牌的数据
    AllTradeMarkList.value=result.data;
    //spu对应的商品图片
    imgList.value=result1.data;
    imgList.value=result1.data.map(item=>{
        return{
            name: item.imgName,
            url: item.imgUrl,
        }
    })
    //已有的SPU销售属性
    saleAttr.value=result2.data;
    //全部的销售属性
    allSaleAttr.value=result3.data;

}


//照片墙点击预览按钮的时候触发的钩子
const handlePictureCardPreview:UploadProps['onPreview']=(uploadFile)=>{
    //对话框弹出
    dialogVisible.value=true;
    dialogImageUrl.value = uploadFile.url as string;
    
}
//照片墙删除文件钩子
const handleRemove: UploadProps['onRemove'] = (uploadFile, uploadFiles) => {
  console.log(uploadFile, uploadFiles)
}

//照片墙上传之前的方法
const handlerUpload=(file:any)=>{
    if(file.type=='image/png' || file.type=='image/jpeg' || file.type=='image/gif'){
        if(file.size>1024*1024*3){
            ElMessage.error("文件过大")
            return false;
        }
        return true;
    }
    else{
        ElMessage.error("上传文件类型错误");
        return false;
    }
}

//计算出当前SPU还未拥有的销售属性
let unSelectSaleAttr=computed(()=>{
    //全部销售属性
    let unSelectArr=allSaleAttr.value.filter(item=>{
        return saleAttr.value.every(item1=>{
            return item.name!=item1.saleAttrName
        });
    })
    return unSelectArr;
})

//添加销售属性的方法
const addSaleAttr=()=>{
    const [baseSaleAttrId,saleAttrName]= saleAttrIdAndValueName.value.split(':');
    //准备新的销售属性
    let newSaleAttr:SaleAttr={
        baseSaleAttrId: Number(baseSaleAttrId),
        saleAttrName: saleAttrName,
        spuSaleAttrValueList: [],
    }
    //追加到数组当中
    saleAttr.value.push(newSaleAttr);
}
//属性值按钮的点击事件
const toEdit=(row:SaleAttr)=>{
    //点击按钮的时候,编辑模式
    row.flag=true;
    row.saleAttrValue='';
}

//表单元素失去焦点的回调
const toLook=(row: SaleAttr)=>{
    //整理收集到的属性的ID与属性值的名字
    const {baseSaleAttrId,saleAttrValue}=row;
    //整理成服务器需要的属性值形式
    let newSaleAttrValue:SaleAttrValue={
        baseSaleAttrId:baseSaleAttrId,
        saleAttrValueName: saleAttrValue as string,
    }
    //非法的情况判断
    if((saleAttrValue as string) .trim()==''){
        ElMessage.error("属性值不能为空");
        return;
    }
    //判断属性值是否在数组当中存在
    let repeat= row.spuSaleAttrValueList.some(item=>{
        return item.saleAttrValueName==saleAttrValue
    })
    if(repeat){
        ElMessage.error("属性值不能重复");
        return ;
    }
    //追加新的属性值对象
    row.spuSaleAttrValueList.push(newSaleAttrValue);
    //切换为查看模式
    row.flag=false;
}

//保存按钮的回调
const save=async ()=>{
    //整理参数
    //照片墙数据
    SpuParams.value.spuImageList=imgList.value.map((item: any)=>{
        return{
            imgName: item.name,
            imgUrl:(item.response&&item.response.data)||item.url,
        }
    });
    SpuParams.value.spuSaleAttrList=saleAttr.value
    //发请求
    let result= await reqAddOrUpdateSpu(SpuParams.value);
    console.log("更改SPU");
    console.log(result);
    if(result.code==200){
        ElMessage({
            type: 'success',
            message: SpuParams.value.id?'更新成功':'添加成功',
        })
    }
    else{
        ElMessage({
            type: 'error',
            message: SpuParams.value.id?'更新失败':'添加失败',
        })
    }
    //通知父组件切换场景
    $emit('changeScene',{flag: 0,params: SpuParams.value.id?'update':'add'});
}

//添加一个新的SPU初始化请求的方法
const initAddSpu =async (c3Id: number|string)=>{
    //清空数据
    Object.assign(SpuParams.value,{
    id: '',
    category3Id: '',
    spuName: '',
    description: '',
    tmId: '',
    spuImageList: [],
    spuSaleAttrList: [],
})

    //清空照片墙
    imgList.value=[];
    //清空销售属性
    saleAttr.value=[];
    saleAttrIdAndValueName.value='';

    //存储三级分类的ID
    SpuParams.value.category3Id=c3Id;
    let result:AllTradeMark= await reqAllTradeMark();
    let result1: HasSaleAttrResponseDate=await reqAllSaleAttr();
    //存储数据
    console.log("父组件获取SPU数据")
    console.log("SPU品牌")
    console.log(result);
    AllTradeMarkList.value=result.data;
    allSaleAttr.value=result1.data;
}









defineExpose({initHasSpuData,initAddSpu})
</script>
<style scoped></style>